package cn.itlaobing.springbootdemo.web.tags;

import org.apache.log4j.Logger;
import org.springframework.data.domain.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 分页标签
 */
public class PaginationTag<T> extends SimpleTagSupport{

   private  Logger logger=Logger.getLogger(PaginationTag.class);

    private Page<T> value;
    private static final String REQUEST_URI_ATTRIBUTE_KEY="javax.servlet.forward.request_uri";

    public void setValue(Page<T> value) {
        this.value = value;
    }

    @Override
    public void doTag() throws JspException, IOException {
        //取得输出流
        JspWriter writer=this.getJspContext().getOut();
        StringBuilder sb=new StringBuilder();
        sb.append("<ul class='pagination pagination-sm pull-right'>");
        generatePreious(sb);//上一页
        generateNumber(sb);
        generateNext(sb);//下一页
        sb.append("</ul>");

        writer.write(sb.toString());
    }

    /**
     * 生成上一页按钮
     * @param sb
     */
    private void generatePreious(StringBuilder sb){

        sb.append("<li class='"+(value.hasPrevious()?"":"disabled")+"'>");
        sb.append("<a href='"+(value.hasPrevious()?getHref(value.getNumber()-1):"#")+"' aria-label='上一页'>");
        sb.append("<span aria-hidden='true'>«</span>");
        sb.append("</a>");
        sb.append("</li>");
    }

    /**
     * 根据页码生成连接地址
     * @param index
     * @return
     */
    private String getHref(int index){
        //获取request对象
        PageContext pageContext=(PageContext)this.getJspContext();
        HttpServletRequest request=(HttpServletRequest)pageContext.getRequest();
        //调试信息 将request范围中所有的数据取出来
//        Enumeration<String> enumeration=request.getAttributeNames();
//        while(enumeration.hasMoreElements()){
//            String key=enumeration.nextElement();
//            Object value=request.getAttribute(key);
//            logger.info(key+">>>>>"+value);
//        }

        //取出请求的地址
        String requestsUri=request.getAttribute(REQUEST_URI_ATTRIBUTE_KEY).toString();

        //取得request中所有的请求参数
        Map<String,String[]> parameterMap=new HashMap<>(request.getParameterMap());
        //删除页码的参数，因为页码的参数是拼接的,页码的参数名称为index
        parameterMap.remove("page");

        //开始拼接参数
        StringBuilder sb=new StringBuilder();
        for(Map.Entry<String,String[]> entry:parameterMap.entrySet()){
            if(entry.getValue().length>1){ //多个同名参数
                for(int i=0;i<entry.getValue().length;i++){
                    sb.append(buildParam(entry.getKey(),entry.getValue()[i]));
                }
            }else{
               sb.append(buildParam(entry.getKey(),entry.getValue()[0]));
            }
        }
        if(sb.length()>1){
            sb.deleteCharAt(sb.length()-1);//删除最后一个 &
        }

        if(sb.length()>0){
            return requestsUri+"?page="+index+"&"+sb.toString();
        }
        return requestsUri+"?page="+index;


    }

    public String buildParam(String parameterName,String parameterValue){
        return parameterName+"="+parameterValue+"&";
    }

    /**
     * 生成下一页按钮
     * @param sb
     */
    private void generateNext(StringBuilder sb){
        sb.append("<li class='"+(value.hasNext()?"":"disabled")+"'>");
        sb.append("<a href='"+(value.hasNext()?getHref(value.getNumber()+1):"#")+"' aria-label='下一页'>");
        sb.append("<span aria-hidden='true'>»</span>");
        sb.append("</a>");
        sb.append("</li>");
    }

    /**
     * 生成页码按钮
     * @param sb
     */
    private void generateNumber(StringBuilder sb){
        for(int i=0;i<value.getTotalPages();i++){
            sb.append("<li class='"+(value.getNumber()==i?"active":"")+"'>");
            sb.append("<a href='"+getHref(i)+"'>");
            sb.append(i+1);
            sb.append("</a>");
            sb.append("</li>");
        }


    }


}
